package com.yugao.fintech.libra.workflow.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageHelper;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageInfo;
import com.yugao.fintech.meheco.core.constant.StatusConstants;
import com.yugao.fintech.meheco.core.exception.FlowException;
import com.yugao.fintech.meheco.core.exception.workflow.WorkflowException;
import com.yugao.fintech.draper.security.utils.SecurityUtils;
import com.yugao.fintech.libra.auth.api.model.SysUser;
import com.yugao.fintech.libra.workflow.api.constant.FlowConstants;
import com.yugao.fintech.libra.workflow.api.model.FlowInfo;
import com.yugao.fintech.libra.workflow.constant.FlowComment;
import com.yugao.fintech.libra.workflow.constant.ProcessConstants;
import com.yugao.fintech.libra.workflow.domain.FlowDefRelation;
import com.yugao.fintech.libra.workflow.domain.FlowTaskRelation;
import com.yugao.fintech.libra.workflow.domain.dto.FlowProcDefDto;
import com.yugao.fintech.libra.workflow.service.AbstractFlowService;
import com.yugao.fintech.libra.workflow.service.IFlowDefinitionService;
import com.yugao.fintech.libra.workflow.service.IFlowRelationService;
import org.apache.commons.io.IOUtils;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class FlowDefinitionServiceImpl extends AbstractFlowService implements IFlowDefinitionService {
    @Autowired
    private IFlowRelationService flowRelationService;

    private static final String BPMN_FILE_SUFFIX = ".bpmn";

    /**
     * 流程定义列表
     *
     * @param pageNum  当前页码
     * @param pageSize 每页条数
     * @return 流程定义分页列表数据
     */
    @Override
    public Page<FlowProcDefDto> list(String name, String category, Integer pageNum, Integer pageSize) {
        Page<FlowProcDefDto> page = new Page<>();
        PageHelper.startPage(pageNum, pageSize);
        final List<FlowProcDefDto> dataList = flowRelationService.defList(name, category);
        page.setTotal(new PageInfo(dataList).getTotal());
        page.setRecords(dataList);
        return page;
    }


    /**
     * 导入流程文件
     *
     * @param name
     * @param category
     * @param in
     */
    @Transactional
    @Override
    public void importFile(String name, String category, InputStream in) {
        // 部署
        Deployment deploy = repositoryService.createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in).name(name).category(category).deploy();
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        repositoryService.setProcessDefinitionCategory(definition.getId(), category);
        // 新增流程定义默认挂起
        updateState(deploy.getId(), FlowConstants.STATUS_DEF_DISABLE);
        // 关联表
        flowRelationService.addDef(buildDefRelation(category, deploy.getId(), definition.getId()));
    }

    private FlowDefRelation buildDefRelation(String category, String deployId, String procDefId) {
        FlowDefRelation flowDefRelation = new FlowDefRelation();
        flowDefRelation.setCategory(category);
        flowDefRelation.setDeployId(deployId);
        flowDefRelation.setProcDefId(procDefId);
        flowDefRelation.setStatus(FlowConstants.STATUS_DEF_DISABLE);
        return flowDefRelation;
    }

    /**
     * 读取xml
     *
     * @param deployId
     * @return
     */
    @Transactional
    @Override
    public String readXml(String deployId) throws IOException {
        ProcessDefinition definition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        InputStream inputStream = repositoryService.getResourceAsStream(definition.getDeploymentId(), definition.getResourceName());
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
    }

    @Transactional
    @Override
    public void startProcess(FlowInfo flowInfo) {
        FlowDefRelation flowDefRelation = flowRelationService.queryDefByCategory(flowInfo.getCategory());
        ProcessInstance processInstance = startProcess(flowDefRelation.getProcDefId(), new HashMap<>());
        flowRelationService.addTask(buildTaskRelation(flowInfo, processInstance));
    }

    private FlowTaskRelation buildTaskRelation(FlowInfo flowInfo, ProcessInstance processInstance) {
        FlowTaskRelation flowTaskRelation = new FlowTaskRelation();
        flowTaskRelation.setFlowCode(flowInfo.getCode());
        flowTaskRelation.setFlowName(flowInfo.getName());
        flowTaskRelation.setRefId(flowInfo.getRefId());
        flowTaskRelation.setStatus(StatusConstants.AUDIT_DOING);
        flowTaskRelation.setProcInsId(processInstance.getId());
        return flowTaskRelation;
    }

    /**
     * 根据流程定义ID启动流程实例
     *
     * @param procDefId 流程定义Id
     * @param variables 流程变量
     * @return
     */
    private ProcessInstance startProcess(String procDefId, Map<String, Object> variables) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(procDefId).latestVersion().singleResult();
        if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
            throw new WorkflowException("流程已被挂起，请先激活流程");
        }
        // 设置流程发起人Id到流程中
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        identityService.setAuthenticatedUserId(sysUser.getUserId().toString());
        variables.put(ProcessConstants.PROCESS_INITIATOR, "");
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(procDefId, variables);
        // 给第一步申请人节点设置任务执行人和意见
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
        if (Objects.nonNull(task)) {
            taskService.addComment(task.getId(), processInstance.getProcessInstanceId(), FlowComment.NORMAL.getType(), sysUser.getNickName() + "发起流程申请");
            taskService.complete(task.getId(), variables);
        }
        return processInstance;
    }


    /**
     * 激活或挂起流程定义
     *
     * @param state    状态
     * @param deployId 流程部署ID
     */
    @Transactional
    @Override
    public void updateState(String deployId, Integer state) {
        ProcessDefinition procDef = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        if (state == 1) { // 激活
            FlowDefRelation flowDefRelation = flowRelationService.queryDefByCategory(procDef.getCategory());
            if (Objects.nonNull(flowDefRelation)) {
                throw new FlowException("只能有一个被激活的同类流程");
            }
            repositoryService.activateProcessDefinitionById(procDef.getId(), true, null);
        } else if (state == 2) { // 挂起
            repositoryService.suspendProcessDefinitionById(procDef.getId(), true, null);
        } else {
            throw new FlowException("状态码错误");
        }
        // 同步更新关联表中的状态
        flowRelationService.editDefStatusByDeployId(deployId, state);
    }


    /**
     * 删除流程定义
     *
     * @param deployId 流程部署ID act_ge_bytearray 表中 deployment_id值
     */
    @Transactional
    @Override
    public void delete(String deployId) {
        flowRelationService.removeDefByDeployId(deployId);
        repositoryService.deleteDeployment(deployId, true);
    }

}
